<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      class="u-mb20"
      v-permission="['account_advertiser_page']"
      v-if="['create', 'edit', 'detail'].includes(pageAction)"
    >
      <el-breadcrumb-item>
        <span
          class="c-text-high u-cursor"
          @click="back"
        >广告主账户管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>账户信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 账号信息 -->
    <SectionContainer class="u-p20 u-mb40">
      <Tabs
        v-if="['edit', 'detail', 'wait', 'refuse', 'header', 'audit'].includes(pageAction)"
        class="u-mb20"
      >
        <TabsItem is-active>账户信息</TabsItem>
        <TabsItem @click="$router.push({
          name: 'account-advertiser-aptitude',
          query: {
            action: $route.query.action,
            userId,
            query: {
              action: $route.query.action,
              userType: $route.query.userType,
              userId
            }
          }
        })">广告投放资质</TabsItem>
      </Tabs>

      <Audit v-if="['detail', 'header'].includes(pageAction)">
        <AuditItem
          :class="{
          'c-hint-succ': baseData.accountStatus === '启用',
          'c-hint-warn': baseData.accountStatus !== '启用'
        }"
          v-html="getAccountStatusTitle(baseData.accountStatus)"
        ></AuditItem>
      </Audit>

      <el-form
        ref="baseForm"
        :model="baseData"
        :rules="baseRules"
        label-width="160px"
      >
        <!--账号信息-->
        <SectionTitle class="u-pt20 u-mb30">账号信息</SectionTitle>
        <div class="u-pb20">
          <el-form-item prop="accountName">
            <span slot="label">
              账户名称
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                content="创建成功后广告主名称不可修改"
              >
                <i class="iconfont iconfont-10 c-hint-major"></i>
              </el-tooltip>
            </span>
            <el-input
              class="u-w440"
              placeholder="产品名称+公司名称"
              v-model="baseData.accountName"
              :disabled="isDisabled(['审核拒绝'])"
            ></el-input>
            <ShowWordLimit
              :value="baseData.accountName"
              :maxlength="20"
            ></ShowWordLimit>
          </el-form-item>
          <el-form-item
            prop="username"
            label="登录账号"
          >
            <el-input
              class="u-w440"
              placeholder="请填写邮箱账号，不可重复"
              v-model="baseData.username"
              :disabled="isDisabled()"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="roleId"
            label="角色"
          >
            <el-radio-group
              v-model="baseData.roleId"
              :disabled="isDisabled()"
            >
              <el-radio
                class="u-lh40"
                v-for="(item, index) in roleOptions"
                :key="index"
                :label="item.id"
              >{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="导入数据账户">
            <el-checkbox
              v-model="baseData.importData"
              :true-label="1"
              :false-label="0"
              :disabled="isDisabled()"
            >{{baseData.importData === 1 ? '是' : '否'}}</el-checkbox>
          </el-form-item>
        </div>

        <!--基本信息-->
        <SectionTitle class="u-pt30 u-mb30">基本信息<Tip
            inline
            class="c-hint-error"
          >（信息修改必须提交账户审核，否则无法正常投放广告）</Tip>
        </SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="company"
            label="公司名称"
          >
            <el-input
              class="u-w440"
              placeholder="请输入公司名称"
              v-model="baseData.company"
              :disabled="isDisabled()"
            ></el-input>
          </el-form-item>
          <el-form-item prop="industryType">
            <span slot="label">
              投放产品行业
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                content="请选择营业执照包含的经营范围"
              >
                <i class="iconfont iconfont-10 c-hint-major"></i>
              </el-tooltip>
            </span>
            <CompanyIndustry
              :value.sync="baseData.industryType"
              :disabled="isDisabled()"
            ></CompanyIndustry>
          </el-form-item>
          <el-form-item
            prop="domainName"
            label="推广域名"
          >
            <el-input
              class="u-w440"
              placeholder="请输入推广域名"
              v-model="baseData.domainName"
              :disabled="isDisabled()"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="companyWebsite"
            label="主页网址"
          >
            <el-input
              class="u-w440"
              placeholder="请输入主页网址"
              v-model="baseData.companyWebsite"
              :disabled="isDisabled()"
            ></el-input>
            <el-button
              class="u-ml10"
              @click="openWindow(baseData.companyWebsite)"
              type="primary"
            >预览</el-button>
          </el-form-item>
        </div>

        <!--其他信息-->
        <SectionTitle class="u-pt30 u-mb30">其他信息</SectionTitle>
        <div class="u-mb30">
          <el-form-item
            prop="name"
            label="联系人"
          >
            <el-input
              class="u-w440"
              placeholder="请输入联系人"
              v-model="baseData.name"
              :disabled="isDisabled()"
            ></el-input>
            <ShowWordLimit
              :value="baseData.name"
              :maxlength="20"
            ></ShowWordLimit>
          </el-form-item>
          <el-form-item
            prop="phone"
            label="联系电话"
          >
            <el-input
              class="u-w440"
              placeholder="请输入联系电话"
              v-model="baseData.phone"
              :disabled="isDisabled()"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="postalAddress"
            label="公司地址"
          >
            <el-input
              type="textarea"
              autosize
              class="u-w440"
              placeholder="请输入公司地址"
              v-model="baseData.postalAddress"
              :disabled="isDisabled()"
            ></el-input>
            <ShowWordLimit
              :value="baseData.postalAddress"
              :maxlength="50"
            ></ShowWordLimit>
          </el-form-item>
          <template v-if="pageAction === 'detail'">
            <el-form-item label="最后操作人">
              {{baseData.updateBy}}
            </el-form-item>
            <el-form-item label="最后操作时间">
              {{baseData.updateDate}}
            </el-form-item>
          </template>
        </div>
      </el-form>
    </SectionContainer>

    <div
      class="u-affix-bottom u-page-handle"
      v-if="['create', 'edit', 'detail'].includes(pageAction)"
    >
      <el-button
        v-if="['create', 'edit'].includes(pageAction)"
        size="small"
        type="primary"
        @click="saveAndBack"
      >保存并返回</el-button>
      <el-button
        v-if="['create'].includes(pageAction) || (pageAction === 'edit' && ['启用', '资质待提交', '审核拒绝'].includes(baseData.accountStatus))"
        size="small"
        type="primary"
        @click="saveAndAptitude"
      >保存并上传资质</el-button>
      <el-button
        v-if="['create', 'edit', 'detail'].includes(pageAction)"
        size="small"
        @click="back"
      >返回</el-button>
    </div>
  </div>
</template>

<script>
import SectionTitle from "@/components/section-title";
import CompanyIndustry from "@/components/company-industry";
import SectionContainer from "@/components/section-container";
import Tabs from "@/components/tabs";
import TabsItem from "@/components/tabs-item";
import ShowWordLimit from "@/components/show-word-limit";
import Tip from "@/components/tip";
import Audit from "./components/audit";
import AuditItem from "./components/audit-item";

import { sessionStorage, getStrLen } from "@/utils";

import {
  fetchAccountBaseAdd,
  fetchAccountBase,
  fetchAccountBaseUpdate,
  fetchAccountDirectRoleSelect
} from "@/api";

export default {
  components: {
    SectionTitle,
    CompanyIndustry,
    SectionContainer,
    Tabs,
    TabsItem,
    ShowWordLimit,
    Tip,
    Audit,
    AuditItem
  },
  data() {
    return {
      pageAction: this.$route.query.action,
      user: sessionStorage.get("USER"),
      userId: this.$route.query.userId,
      baseData: {
        accountStatus: "",
        accountName: "", // 账户名称
        username: "", // 登录账户
        roleId: "", // 角色
        importData: 0, // 导入数据账户
        userType: this.$route.query.userType, // 用户类型：1普通用户、2管理员用户
        company: "", // 公司名称
        industryType: "", // 投放产品行业
        domainName: "", // 推广域名
        companyWebsite: "", // 主页网址
        name: "", // 联系人
        phone: "", // 联系电话
        postalAddress: "" // 公司地址
      },
      baseRules: {
        accountName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入账户名称"));
            } else if (getStrLen(value) > 20) {
              callback(new Error("账户名称不能超过20个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        username: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入登录账户"));
            } else if (!/^\w+@\w+\.\w+$/.test(value)) {
              callback(new Error("请输入正确的邮箱账号"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        roleId: {
          required: true,
          message: "请选择角色",
          trigger: ["blur", "change"]
        },
        company: {
          required: true,
          message: "请输入公司名称",
          trigger: ["blur", "change"]
        },
        industryType: {
          required: true,
          message: "请选择投放产品行业",
          trigger: ["blur", "change"]
        },
        domainName: {
          required: true,
          message: "请输入推广域名",
          trigger: ["blur", "change"]
        },
        companyWebsite: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入主页网址"));
            } else if (!/^https?:\/\//.test(value)) {
              callback(new Error("请输入以http或https开头的主页网址"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        name: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入联系人"));
            } else if (getStrLen(value) > 20) {
              callback(new Error("联系人不能超过20个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        phone: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入联系电话"));
            } else if (!/^(\d{3,4}-?\d{7,8})$|^(1\d{10})$/.test(value)) {
              callback(new Error("请输入正确的联系电话"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        postalAddress: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入公司地址"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("公司地址不能超过50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },
      roleOptions: []
    };
  },
  computed: {
    submitData() {
      let {
        accountName,
        username,
        userType,
        company,
        industryType,
        domainName,
        companyWebsite,
        name,
        phone,
        postalAddress,
        importData
      } = this.baseData;
      return {
        accountName,
        username,
        userType,
        company,
        industryType,
        domainName,
        companyWebsite,
        name,
        phone,
        postalAddress,
        importData
      };
    }
  },
  methods: {
    // 获取内部审核状态title
    getAccountStatusTitle(v) {
      if (v === "启用") {
        return `<i class='el-icon-success u-fs16 u-vat u-mt3'></i> 账号状态：${v}`;
      }
      return `<i class='el-icon-warning u-fs16 u-vat u-mt3'></i> 账号状态：${v}`;
    },
    // 打开新页面
    openWindow(url) {
      if (url) {
        window.open(url);
      }
    },
    // 角色
    fetchAccountDirectRoleSelect() {
      return fetchAccountDirectRoleSelect().then(res => {
        this.roleOptions = res.data.list || [];
        if (this.pageAction === "create") {
          this.baseData.roleId =
            this.roleOptions.length && this.roleOptions[0].id;
        }
      });
    },
    // 是否禁用编辑
    isDisabled(status = []) {
      if (this.pageAction === "create") {
        return false;
      } else if (this.pageAction === "edit") {
        return status.includes(this.baseData.accountStatus);
      }
      return true;
    },
    // 返回
    back() {
      this.$router.replace({
        name: "account-advertiser-man",
        query: {
          ...this.$route.query.query
        }
      });
    },
    // 保存并返回
    saveAndBack() {
      this.$refs["baseForm"].validate((valid, params) => {
        if (valid) {
          if (this.pageAction === "create") {
            // 新建
            this.fetchAccountBaseAdd({
              query: {
                userId: this.user.userId
              }
            }).then(() => {
              setTimeout(() => {
                this.back();
              }, 1000);
            });
          } else {
            // 编辑、查看
            this.fetchAccountBaseUpdate().then(() => {
              setTimeout(() => {
                this.back();
              }, 1000);
            });
          }
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 保存并上传资质
    saveAndAptitude() {
      this.$refs["baseForm"].validate((valid, params) => {
        if (valid) {
          if (this.pageAction === "create") {
            // 新建
            this.fetchAccountBaseAdd({
              query: {
                userId: this.user.userId
              }
            }).then(res => {
              this.userId = res.data.userId;
              setTimeout(() => {
                this.$router.push({
                  name: "account-advertiser-aptitude",
                  query: {
                    action: this.$route.query.action,
                    userId: this.userId,
                    query: {
                      action: this.$route.query.action,
                      userId: this.userId,
                      userType: this.$route.query.userType
                    }
                  }
                });
              }, 1000);
            });
          } else {
            // 编辑、查看
            this.fetchAccountBaseUpdate().then(() => {
              this.userId = this.$route.query.userId;
              setTimeout(() => {
                this.$router.push({
                  name: "account-advertiser-aptitude",
                  query: {
                    action: this.$route.query.action,
                    userId: this.userId,
                    query: {
                      action: this.$route.query.action,
                      userId: this.userId,
                      userType: this.$route.query.userType
                    }
                  }
                });
              }, 1000);
            });
          }
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 获取账户信息
    fetchAccountBase() {
      fetchAccountBase({
        query: {
          userId: this.$route.query.userId
        }
      }).then(res => {
        this.baseData = res.data;
      });
    },
    // 新增账户信息
    fetchAccountBaseAdd() {
      return fetchAccountBaseAdd({
        query: {
          userId: this.user.userId,
          roleId: this.baseData.roleId
        },
        body: this.submitData
      }).then(res => {
        this.$message({
          message: "账户信息新增成功",
          duration: 1000
        });
        return res;
      });
    },
    // 更新账户信息
    fetchAccountBaseUpdate() {
      return fetchAccountBaseUpdate({
        query: {
          roleId: this.baseData.roleId
        },
        body: {
          ...this.submitData,
          id: this.$route.query.userId
        }
      }).then(() => {
        this.$message({
          message: "账户信息修改成功",
          duration: 1000
        });
      });
    }
  },
  created() {
    this.fetchAccountDirectRoleSelect().then(() => {
      if (this.pageAction !== "create") {
        this.fetchAccountBase();
      }
    });
  }
};
</script>